<template>
  <div>
    <scroller>
      <div class="text-center p-3">
        <image class="qr-img mb-1"
               :src="qrcode"></image>
        <text>{{appName}}</text>
        <text class="text-muted small">{{appVersionName}}</text>
        <text class="text-muted small"
              v-if="!isRelease">(开发环境)</text>
      </div>

      <div class="p-3">
        <text class="mb-3">版本信息</text>
        <text class="text-muted small">{{newest.description || '-'}}</text>
      </div>
    </scroller>

    <div class="p-1">
      <vm-button type="white"
                 text="检查更新"
                 @buttonClicked="checkVersion(true)"></vm-button>
    </div>
  </div>
</template>
<script>
import vmButton from '../../components/vm-button.vue'
import domain from '../../plugins/domain'
// import { APP_DOWNLOAD_URL } from '../../plugins/constant'

export default {
  components: {
    vmButton
  },
  props: {},
  data() {
    return {
      qrcode: '',
      appName: weex.config.env.appName,
      appVersionName: weex.config.env.appVersion,
      isRelease: false, // /.*\.com$/.test(weex.config.env.request),
      appVersionInfo: {},
      newest: {},
      errorMsg: '无法获取更新信息，请稍后再试',
      downloadUrl: ''
    }
  },
  computed: {},
  watch: {},
  created() {
    this.isRelease = weex.config.env.request === domain.releaseUrl
    this.$navigator.setRightItem({
      image: 'bmlocal://assets//icon_share.png'
    }, this.shareButtonClick)
  },
  mounted() {
    this.checkVersion()
  },
  methods: {
    async gQrcode() {
      this.qrcode = await this.$picture.qrcode({ url: this.downloadUrl || 'http://www.vimi8.com/app' })
    },
    checkVersion(showMsg = false) {
      this.$notice.loading.show()
      Promise.all([this.getVersionInfo(), this.getNesest()]).then(res => {
        this.appVersionInfo = res[0] || {}
        this.newest = res[1] || {}
        this.getDownloadUrl().then(res => {
          this.downloadUrl = res
          this.checkUpdate(showMsg)
        }).catch(err => {
          if (showMsg) {
            this.$notice.toast({ message: '获取更新失败' })
          }
        }).finally(() => {
          this.gQrcode()
        })
      }).catch(err => {
        this.$notice.toast({ message: err.gmMessage || this.errorMsg })
      }).finally(() => {
        this.$notice.loading.hide()
      })
    },
    getVersionInfo() {
      return new Promise(async (resolve, reject) => {
        const [res, err] = await this.$utils.pm(this.$version.getVersionInfo())
        if (res) { resolve(res) } else { reject(err) }
      })
    },
    getNesest() {
      return new Promise(async (resolve, reject) => {
        const [res, err] = await this.$utils.pm(this.$api.getData({
          server: 'agr_chain',
          table: 'app_version_view',
          params: {
            index: 1,
            size: 1,
            'release_status.eq': 1
          },
          order: {
            version_code: 'desc'
          },
          errorMsg: '获取数据失败'
        }))
        if (res && res.data && res.data.length) {
          const item = res.data[0]
          item.links = []
          item.description = item.description ? item.description.replace(/<br\/>/g, '\n').replace(/&nbsp;/g, ' ') : ''
          const channelNames = this.getSplit(item.channel_name)
          const channelUrls = this.getSplit(item.channel_url)
          const channelIds = this.getSplit(item.channel_id)
          for (let i = 0; i < channelNames.length; i++) {
            item.links.push({
              channelId: channelIds[i],
              channelName: channelNames[i],
              channelUrl: channelUrls[i]
            })
          }
          resolve(item)
        } else {
          reject(err)
        }
      })
    },

    getSplit(str, splitor = ',') {
      return str ? str.split(splitor) : []
    },

    // 检查是否需要更新
    checkUpdate(showMsg = false) {
      // 无法获取版本信息
      if (!this.appVersionInfo.versionCode || !this.newest.version_code) {
        if (showMsg) {
          this.$notice.toast({ message: this.errorMsg })
        }
        return
      }

      // 版本号不一致
      if (this.appVersionInfo.versionCode < +this.newest.version_code) {
        this.$dialog.show({
          title: '发现新版本',
          content: this.newest.description || '',
          positiveText: '更新',
          negativeText: '取消',
          onPositive: () => {
            this.startDownloadAndInstall()
          }
        })
      } else {
        if (showMsg) {
          this.$notice.toast({ message: '已经是最新版本' })
        }
      }
    },
    startDownloadAndInstall() {
      if (!this.downloadUrl) {
        return this.$notice.toast({ message: '无下载地址' })
      }
      this.$version.downloadAndInstall({
        downloadUrl: this.downloadUrl,
        versionTips: this.newest.version_tips
      }).then(res => {
        this.$notice.toast({ message: '开始下载，下载完成后自动安装' })
      }).catch(err => {
        this.$notice.toast({ message: '更新失败，请稍后再试' })
      })
    },
    // 从最新版本获取对应渠道的下载地址
    getDownloadUrl() {
      return new Promise((resolve, reject) => {
        const links = this.newest.links || []
        if (!links.length) {
          return reject('无下载地址')
        }
        let downloadUrl = ''
        let defaultUrl = ''
        for (const link of links) {
          if (link.channelId === this.appVersionInfo.channel) {
            downloadUrl = link.channelUrl
            break
          }
          if (link.channelId === 'WeiMi') {
            defaultUrl = link.channelUrl
          }
        }
        if (!downloadUrl) {
          downloadUrl = defaultUrl
        }
        if (!downloadUrl) {
          reject('无下载地址')
        } else {
          resolve(downloadUrl)
        }
      })
    },
    async shareButtonClick() {
      const [res] = await this.$utils.pm(this.$version.getVersionInfo())
      if (!res) {
        return this.$notice.toast({ message: '获取应用分享地址失败！' })
      }
      const versionName = res.versionName
      const versionType = this.isRelease ? 'release' : 'debug'
      this.$share.url({
        title: '为米养鸡',
        url: this.downloadUrl,
        description: '',
        image: ''
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.text-center {
  text-align: center;
  align-items: center;
}
.p-3 {
  padding: 30px;
}
.p-1 {
  padding: 10px;
}
.mb-1 {
  margin-bottom: 10px;
}
.mb-3 {
  margin-bottom: 30px;
}
.text-muted {
  color: #999;
}
.small {
  font-size: 26px;
}

.qr-img {
  width: 360px;
  height: 360px;
}
</style>
